package vip.xiaonuo.common.util;

import lombok.extern.slf4j.Slf4j;
import vip.xiaonuo.common.pojo.ExcelCalleeVo;
import vip.xiaonuo.common.wechat.EmailExcelUtils;
import vip.xiaonuo.common.wechat.MailSender;

import javax.mail.MessagingException;
import java.io.File;
import java.util.List;

@Slf4j
public class AttachmentMailSenderUtil {

    //发送带附件的email
    public static void sendFileEmail(List<ExcelCalleeVo> dataList, String[] toAddress, String username, String password) throws MessagingException {
        try {
            // 生成Excel
            String excelPath = EmailExcelUtils.createExcel(dataList);

            // 发送邮件
            for (String to : toAddress) {
                MailSender.sendWithAttachment("smtp.163.com", username, password, to, excelPath);
                log.info("邮件发送成功");
                //休眠等待邮件发送成功
                Thread.sleep(5000);
            }

            //删除临时文件 excelPath
            File excelFile = new File(excelPath);
            if (excelFile.exists() && excelFile.delete()) {
                log.info("临时文件删除成功");
            }

        } catch (Exception e) {
            log.error("邮件发送异常：", e);
        }
    }
}
